<?php
/**
 * Created by JetBrains PhpStorm.
 * User: dodasso
 * Date: 7/21/13
 * Time: 10:17 PM
 * To change this template use File | Settings | File Templates.
 */

namespace common;

require_once(APP_ROOT . '/modules/log/log.php');
require_once(APP_ROOT . '/modules/log/logCommon.php');
require_once(APP_ROOT . '/modules/common/Common.php');

use log\Log;
use log\LogCommon;

class Utils {
    /**
     * @param $decrypted
     * @return bool|string
     */
    public static function encrypt($decrypted) {
        // Build a 256-bit $key which is a SHA256 hash of $salt and $password.
        $key = hash('SHA256', Common::salt . Common::secret, true);
        // Build $iv and $iv_base64.  We use a block size of 128 bits (AES compliant) and CBC mode.  (Note: ECB mode is inadequate as IV is not used.)
        srand(); $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC), MCRYPT_RAND);
        if (strlen($iv_base64 = rtrim(base64_encode($iv), '=')) != 22) return false;
        // Encrypt $decrypted and an MD5 of $decrypted using $key.  MD5 is fine to use here because it's just to verify successful decryption.
        $encrypted = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $decrypted . md5($decrypted), MCRYPT_MODE_CBC, $iv));
        // We're done!
        return $iv_base64 . $encrypted;
    }

    /**
     * @param $encrypted
     * @return bool|string
     */
    public static function decrypt($encrypted) {
        // Build a 256-bit $key which is a SHA256 hash of $salt and $password.
        $key = hash('SHA256', Common::salt . Common::password, true);
        // Retrieve $iv which is the first 22 characters plus ==, base64_decoded.
        $iv = base64_decode(substr($encrypted, 0, 22) . '==');
        // Remove $iv from $encrypted.
        $encrypted = substr($encrypted, 22);
        // Decrypt the data.  rtrim won't corrupt the data because the last 32 characters are the md5 hash; thus any \0 character has to be padding.
        $decrypted = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, base64_decode($encrypted), MCRYPT_MODE_CBC, $iv), "\0\4");
        // Retrieve $hash which is the last 32 characters of $decrypted.
        $hash = substr($decrypted, -32);
        // Remove the last 32 characters from $decrypted.
        $decrypted = substr($decrypted, 0, -32);
        // Integrity check.  If this fails, either the data is corrupted, or the password/salt was incorrect.
        if (md5($decrypted) != $hash) return false;
        // Yay!
        return $decrypted;
    }

    /**
     * @return string
     */
    public static function uuid() {
        Log::LOG_COMMON_FB();

        $uuid = sprintf( '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
            // 32 bits for "time_low"
            mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ),
            // 16 bits for "time_mid"
            mt_rand( 0, 0xffff ),
            // 16 bits for "time_hi_and_version",
            // four most significant bits holds version number 4
            mt_rand( 0, 0x0fff ) | 0x4000,
            // 16 bits, 8 bits for "clk_seq_hi_res",
            // 8 bits for "clk_seq_low",
            // two most significant bits holds zero and one for variant DCE1.1
            mt_rand( 0, 0x3fff ) | 0x8000,
            // 48 bits for "node"
            mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ));

        Log::LOG_COMMON_FE();

        return $uuid;
    }

    /**
     * @param $array
     * @return null|string
     */
    public static function buildResponse($array) {
        Log::LOG_COMMON_FB();

        if((is_null($array['error'])) || (!is_int($array['error']))) {
            return null;
        }

        $rs['errorCode'] = $array['error'];
        if($array['error'] != Errors::INTEGRAL_ERR_NONE) {
            $rs['displayMsg'] = 'An error has been detected. See the server logs.';
        } else {
            $rs['displayMsg'] = 'Success';
        }

        if((array_key_exists('data', $array)) && (!is_null($array['data']))) {
            $rs['data'] =  $array['data'];
        }

        Log::LOG_COMMON_FE();

        return json_encode($rs);
    }
}